# Title     : TODO
# Objective : TODO
# Created by: xueyj
# Created on: 2020/10/13 0013

#pacman::p_load(ggplot2, dplyr, pracma, magrittr, stringr)

suppressMessages(library("ggplot2"))

suppressMessages(library("dplyr"))

suppressMessages(library("pracma"))

suppressMessages(library("magrittr"))

suppressMessages(library("stringr"))

suppressMessages(library("lazyopt"))

getnewdate <- function(path) {
  data <- path %>%
    read.delim(check.names = FALSE) %>%
    select(c("Time", "Weight", "vpd", "BARO/2/VP4", "DIELEC/0/5TM",
             "RH/2/VP4", "TEMP/0/5TM", "TEMP/2/VP4", "VAPORP/2/VP4",
             "vwc", "Tr"))
  k <- data %$% str_split(Time, " ")
  da <- NULL; ti <- NULL
  for (i in seq_along(k)) {
    da[i] <- k[[i]][1]; ti[i] <- k[[i]][2]
  }
  da %<>%
    as.character()
  ti %<>%
    as.character()

  data %>%
    mutate(date = da, time = ti) %>%
    select(c("date", "time", "Weight", "vpd", "BARO/2/VP4", "DIELEC/0/5TM",
             "RH/2/VP4", "TEMP/0/5TM", "TEMP/2/VP4", "VAPORP/2/VP4", "vwc",
             "Tr")) %>%
    return()
}

weightsmooth <- function(a, n = 30) {
  for (i in seq_along(a)) {
    a[i] <- mean(a[i:(i + n - 1)], na.rm = TRUE)
  }
  return(a)
}

bijiaoTime <- function(a, b) {
  a1 <- a %>%
    lazyopt::fenge() %>%
    as.numeric()
  b1 <- b %>%
    lazyopt::fenge() %>%
    as.numeric()
  if ((a1[1] * 60 + a1[2] - b1[1] * 60 - b1[2]) >= 0) {
    return(TRUE)
  }else {
    return(FALSE)
  }
}

add_Gs_Gsc <- function(data) {
  data %>%
    mutate(Gs = Tr / p) %>%
    mutate(Gsc = Gs / vpd) %>%
    return()
}


getmebytime <- function(data, min, max, times) {
  list <- NULL
  list2 <- NULL
  list3 <- NULL
  for (i in seq_along(times)) {
    linshidata <- data[which(data$date == times[i]),]
    index <- NULL
    for (a in seq_len(nrow(linshidata))) {
      k <- linshidata[a, 2]
      index[a] <- ifelse((bijiaoTime(k, min) && bijiaoTime(max, k)), 1, 0)
    }
    list[i] <- linshidata[which(index == 1),] %$%
      mean(Tr, na.rm = TRUE)
    list2[i] <- linshidata[which(index == 1),] %$%
      mean(vwc, na.rm = TRUE)
    list3[i] <- linshidata[which(index == 1),] %$%
      mean(vpd, na.rm = TRUE)
  }
  data.frame(Time = times, Tr = list,
             vwc = list2, vpd = list3) %>%
    return()
}

getmebytime2 <- function(data, min, max, times) {
  list <- NULL
  for (i in seq_along(times)) {
    linshidata <- data[which(data$date == times[i]),]
    index <- NULL
    for (a in seq_len(nrow(linshidata))) {
      k <- linshidata[a, 2]
      index[a] <- ifelse((bijiaoTime(k, min) && bijiaoTime(max, k)), 1, 0)
    }
    list[i] <- linshidata[which(index == 1),] %$% mean(Weight)
  }
  data.frame(Time = times, mean = list) %>% return()
}

getme <- function(path) {
  data <- path %>%
    getnewdate() %>%
    set_colnames(c("date", "time", "Weight", "vpd", "BARO_2_VP4", "DIELEC_0_5TM",
                   "RH_2_VP4", "TEMP_0_5TM", "TEMP_2_VP4", "VAPORP_2_VP4", "Tr",
                   "vwc"))
  times <- data %$% unique(date)
  Tr <- NULL
  vpd <- NULL
  BARO_2_VP4 <- NULL
  DIELEC_0_5TM <- NULL
  RH_2_VP4 <- NULL
  TEMP_0_5TM <- NULL
  TEMP_2_VP4 <- NULL
  vwc <- NULL
  VAPORP_2_VP4 <- NULL
  for (i in seq_along(times)) {
    k <- which(data[, 1] == times[i])
    Tr[i] <- mean((data$Tr)[k])
    vpd[i] <- mean((data$vpd)[k])
    BARO_2_VP4[i] <- mean((data$BARO_2_VP4)[k])
    DIELEC_0_5TM[i] <- mean((data$DIELEC_0_5TM)[k])
    RH_2_VP4[i] <- mean((data$RH_2_VP4)[k])
    TEMP_0_5TM[i] <- mean((data$TEMP_0_5TM)[k])
    TEMP_2_VP4[i] <- mean((data$TEMP_2_VP4)[k])
    VAPORP_2_VP4[i] <- mean((data$VAPORP_2_VP4)[k])
    vwc[i] <- mean((data$vwc)[k])
  }

  m <- data %>%
    getmebytime2("4:00", "4:30", times)
  e <- data %>%
    getmebytime2("19:00", "19:30", times)

  data <- data.frame(Time = m[, 1],
                     m = m[, 2], e = e[, 2])
  data[, 1] %<>%
    as.character() %>%
    as.Date.character() %>%
    as.character()
  data %<>%
    mutate(E = m - e) %>%
    arrange(Time)
  data %<>%
    mutate(p = c((data$m[2:nrow(data)] - data$m[1:(nrow(data) - 1)]) %>% as.numeric(), NA),
           Tr = Tr, vpd = vpd,
           BARO_2_VP4 = BARO_2_VP4, DIELEC_0_5TM = DIELEC_0_5TM,
           RH_2_VP4 = RH_2_VP4, TEMP_0_5TM = TEMP_0_5TM,
           TEMP_2_VP4 = TEMP_2_VP4,
           VAPORP_2_VP4 = VAPORP_2_VP4, vwc = vwc)
  return(data)
}

add_CTr_CGs_CGsc <- function (dd,quezhi){
  result <- dd

  return (result)
}


arg <- c("-i", "E:/projects/Lysimeter_Systems/src/output/A13.xls",
        "-o", "E:/projects/Lysimeter_Systems/src/image2")

opt <- matrix(c(
  "inputfile", "i", 2, "character", "Set the input file path or packagepath", " ",
  "response_threshold","tr",1,"numeric","set response threshold","1",
  "outputpackage", "o", 2, "character", "Set the output folder path", " ",
  "imageformat", "if", 1, "character", "set image type", "pdf",
  "resolution", "dpi", 1, "numeric", "Set the resolution to allow 72,96,300 or 600", "300"
), byrow = TRUE, ncol = 6) %>% lazyopt(arg=NULL)

data <- getnewdate(opt$inputfile)


dd <- getmebytime(data, "12:00", "14:00", unique(data$date))

title <- (opt$inputfile %>%
  basename() %>%
  str_split("-"))[[1]][1]

dd2 <- getme(opt$inputfile)

dd %<>%
  mutate(p = dd2$p) %>%
  add_Gs_Gsc() %>%
  add_CTr_CGs_CGsc(opt$response_threshold)

write.table(dd, file = opt %$%
  paste0(outputpackage, "/", title, "12-14", ".xls"),
            sep = "\t", col.names = NA)

myggplottype <- function(pp) {
  return(pp +
           theme_bw() +
           theme(
             panel.border = element_blank(),
             panel.grid.major = element_blank(),
             panel.grid.minor = element_blank(),
             legend.background = element_blank(),
             axis.text.x = element_text(angle = 270)
           ) +
           coord_trans(x = "reverse"))
}


pp <- ggplot(dd) +
  geom_smooth(aes(x = vwc, y = Tr))

pp %<>%
  myggplottype()

resolution <- match.arg(opt$resolution %>%
                          as.character(), c("72", "96", "300", "600")) %>%
  as.numeric()

ggsave(pp, filename = opt %$%
  paste0(outputpackage, "/", title, "12-14-vwc-Tr", ".", opt$imageformat),
       dpi = resolution)










